// pages/bookingGoods/index/index.js
var app = getApp()
var call = require("../../../utils/request.js");
Page({
  data: {
    offset: 0,// 页码
    limit: 16, // 每页条数
    totalNum: 0, // 数据总条数
    status: false, // 是否还有数据

    timeStatus: true, // 上架时间状态
    priceStatus: true, // 价格状态
    hide_good_box: true,
    good_box_img: '../../../image/commodityDefault.png',
    listData: [],
    total: 0, // 合计
    classificationStatus: false,
    classificationData: [], // 分类数据
    classificationIndex: 10000, // 分类下标
    showModalStatus: false,
    selectedData: [], // 已选产品
    screenStatus: 0, // 筛选状态
    category: '', // 分类筛选值
  },
    
  onLoad: function (options) {
    this.classification() // 获取分类数据
    this.getCommodityData(this.data.offset,this.data.limit)
    this.busPos = {};
    // this.busPos['x'] = app.globalData.ww / 2;
    this.busPos['x'] = 20;
    this.busPos['y'] = app.globalData.hh - 10;
    console.log('购物车坐标',this.busPos)

    let bookingGoodsData = wx.getStorageSync('bookingGoodsData');
    if(bookingGoodsData){ 
      this.total();
      this.setData({ selectedData: bookingGoodsData }) 
    }
  },
  // 获取产品数据
  getCommodityData (offset,limit) {
    let sort = 'id';
    let order = 'desc';
    let category = this.data.category;
    switch(this.data.screenStatus){
      case 2:
        sort = 'release_date'
        this.data.timeStatus ? order = 'desc' : order = 'asc'
        break;
      case 3:
        sort = 'sell_price'
        this.data.priceStatus ? order = 'desc' : order = 'asc'
        break;
    }
    call.getData('/api/goods/glist', { sort,order,category,offset,limit },
    data => {
      if(data.code == 1){
        let listData = this.data.listData;
        for(let item of data.data.rows){
          listData.push(item)
        }
        this.setData({ listData,totalNum: data.data.total })
      }else{
        wx.showToast({ icon: 'none',title: data.msg })
      }
      this.setData({loadStatua: true})
    },
    err => {
      console.log(err)
    },false)
  },
  // 获取分类
  classification () {
    call.getData('/api/goods/category', {},
    data => {
      if(data.code == 1){
        this.setData({ classificationData: data.data})
      }else{
        wx.showToast({ icon: 'none',title: data.msg })
      }
    },
    err => {
      console.log(err)
    },false)
  },
  /**
   * 页面上拉触底事件的处理函数，与点击加载更多做同样的操作
   */
  onReachBottom () {
    let total = this.data.totalNum;  // 总条数
    console.log(total)
    let offset = this.data.offset; // 偏移量
    let limit = this.data.limit; // 当前页显示条数
    this.setData({ offset: offset + 1 })
    offset = (offset + 1 ) * limit;
    console.log(offset)
    if(total > offset){
      console.log(1)
    }else{
      this.setData({ status: true })
    }
   
    if(this.data.status){
      console.log('没有数据了')
    }else{
      wx.showLoading({
        title: '玩命加载中...',
      });
      this.getCommodityData(offset, limit);
      wx.hideLoading();
    }
  },
  // 上架时间和价格筛选
  screen(e){
    this.hideClassificationModal()
    this.setData({ listData: [],offset: 0,status: false })
    let status = e.currentTarget.dataset.status; 
    switch(status){
      case '1':
        this.setData({ screenStatus: 1 })
        break;
      case '2':
        this.setData({ 
          timeStatus: !this.data.timeStatus,
          screenStatus: 2,
          classificationIndex: 10000,
          category: '', 
        })
        break;
      case '3':
        this.setData({ 
          priceStatus: !this.data.priceStatus,
          screenStatus: 3,
          classificationIndex: 10000,
          category: '',  
        })
        break;
    }
    this.getCommodityData(this.data.offset,this.data.limit)
  },
  // 筛选产品
  addActive (e) {
    console.log(e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index;
    this.setData({
      classificationIndex: index,
      category: this.data.classificationData[index].category_name
    })
  },
  // 减少产品
  reduce (e) {
    let data = e.currentTarget.dataset.data;
    let bookingGoodsData = wx.getStorageSync('bookingGoodsData');
    for (let i in bookingGoodsData) {
      if (bookingGoodsData[i].id == data.id) {
        if(bookingGoodsData[i].num == 1){
          bookingGoodsData.splice( i, 1)
        }else{
          bookingGoodsData[i].num --;
        }
      }
    }
    wx.setStorageSync('bookingGoodsData', bookingGoodsData)
    this.setData({selectedData: bookingGoodsData})
    this.total(); // 计算总价
    if(0 in bookingGoodsData == false){
      wx.removeStorageSync('bookingGoodsData');
      this.setData({ showModalStatus: false })
    }
  },
  // 清空已选产品
  empty () {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '是否清空全部已选产品',
      success (res) {
        if (res.confirm) {
          wx.removeStorageSync('bookingGoodsData');
          that.setData({ selectedData: [],total:0 })
          that.hideBuyModal();
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 去结算
  goSettlement () {
    if(this.data.selectedData.length > 0){
      wx.navigateTo({
        url: '/pages/bookingGoods/confirm/index?total=' + this.data.total
      })
    }else{
      wx.showToast({ icon: 'none',title: '请选择产品' })
    }
  },
  classificationModal () {
    if(this.data.classificationStatus){
      return false
    }



    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      /**
        * http://cubic-bezier.com/ 
        * linear 动画一直较为均匀
        * ease 从匀速到加速在到匀速
        * ease-in 缓慢到匀速
        * ease-in-out 从缓慢到匀速再到缓慢
        * 
        * http://www.tuicool.com/articles/neqMVr
        * step-start 动画一开始就跳到 100% 直到动画持续时间结束 一闪而过
        * step-end 保持 0% 的样式直到动画持续时间结束 一闪而过
        */
      timingFunction: "ease",
      delay: 0
  })
  this.animation = animation
  animation.translateY(-300).step()
  this.setData({
      animationClassificationData: animation.export(), // export 方法每次调用后会清掉之前的动画操作。
      classificationStatus: true
  })
  setTimeout(() => {
      animation.translateY(0).step()
      this.setData({
          animationClassificationData: animation.export()  // export 方法每次调用后会清掉之前的动画操作。
      })
      console.log(this)
  }, 200)
  },
  hideClassificationModal () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
        duration: 200,
        timingFunction: "ease",
        delay: 0
    })
    this.animation = animation
    animation.translateY(-300).step()
    this.setData({
        animationClassificationData: animation.export(),
    })
    setTimeout(function () {
        animation.translateY(0).step()
        this.setData({
            animationClassificationData: animation.export(),
            classificationStatus: false,
        })
        console.log(this)
    }.bind(this), 200)
  },
  showBuyModal () {
    if(0 in this.data.selectedData == false || this.data.showModalStatus){
      return false
    }
    // 显示遮罩层
    var animation = wx.createAnimation({
        duration: 200,
        /**
          * http://cubic-bezier.com/ 
          * linear 动画一直较为均匀
          * ease 从匀速到加速在到匀速
          * ease-in 缓慢到匀速
          * ease-in-out 从缓慢到匀速再到缓慢
          * 
          * http://www.tuicool.com/articles/neqMVr
          * step-start 动画一开始就跳到 100% 直到动画持续时间结束 一闪而过
          * step-end 保持 0% 的样式直到动画持续时间结束 一闪而过
          */
        timingFunction: "ease",
        delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
        animationData: animation.export(), // export 方法每次调用后会清掉之前的动画操作。
        showModalStatus: true
    })
    setTimeout(() => {
        animation.translateY(0).step()
        this.setData({
            animationData: animation.export()  // export 方法每次调用后会清掉之前的动画操作。
        })
        console.log(this)
    }, 200)
},

hideBuyModal () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
        duration: 200,
        timingFunction: "ease",
        delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
        animationData: animation.export(),
    })
    setTimeout(function () {
        animation.translateY(0).step()
        this.setData({
            animationData: animation.export(),
            showModalStatus: false
        })
        console.log(this)
    }.bind(this), 200)
},
  // 算总价
  total () {
    let bookingGoodsData = wx.getStorageSync('bookingGoodsData');
    console.log(bookingGoodsData)
    let total = 0;
    for (var item of bookingGoodsData) {
      let num = Math.round(item.sell_price*100)/100 * Math.round(item.num*100)/100;
      item.total =  Math.round(num*100)/100;
      total += Math.round(item.total*100)/100;
    }
    console.log(bookingGoodsData)
    this.setData({ total: Math.round(total*100)/100,selectedData: bookingGoodsData })
    wx.setStorageSync('bookingGoodsData', bookingGoodsData)
  },
  // 返回上一页
  goReturn: function () {
    wx.navigateTo({
      url: '/pages/home/index'
    })
    // let pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
    // let prevPage = pages[pages.length - 2]; 
    // wx.navigateBack({
    //   delta: 1
    // })
  },
  touchOnGoods: function (e) {
    //wx.removeStorageSync('bookingGoodsData')
    let data = e.currentTarget.dataset.data;
    let good_box_img = '';
    0 in data.thumb ? good_box_img = data.thumb[0] : good_box_img = '../../../image/commodityDefault.png';
    
    let bookingGoodsData = wx.getStorageSync('bookingGoodsData');
    if(bookingGoodsData){
      if(bookingGoodsData.length > 0){
        let flag = true;
        for (var item of bookingGoodsData) {
          if (item.id == data.id) {
            item.num ++;
            flag = false;
          }
        }
        if(flag){
          bookingGoodsData.push(data)
        }
        wx.setStorageSync('bookingGoodsData', bookingGoodsData)
      }
    }else{
      wx.setStorageSync('bookingGoodsData', [data])
    }
    
    console.log(bookingGoodsData)
    this.setData({ good_box_img })


    // 如果good_box正在运动
    if (!this.data.hide_good_box) return;
    this.finger = {};
    var topPoint = {};
    this.finger['x'] = e.touches["0"].clientX;
    this.finger['y'] = e.touches["0"].clientY;
    if (this.finger['y'] < this.busPos['y']) {
      topPoint['y'] = this.finger['y'] - 150;
    } else {
      topPoint['y'] = this.busPos['y'] - 150;
    }
    topPoint['x'] = Math.abs(this.finger['x'] - this.busPos['x']) / 2;
    if (this.finger['x'] > this.busPos['x']) {
      topPoint['x'] = (this.finger['x'] - this.busPos['x']) / 2 + this.busPos['x'];
    } else {
      topPoint['x'] = (this.busPos['x'] - this.finger['x']) / 2 + this.finger['x'];
    }
    this.linePos = app.bezier([this.finger, topPoint, this.busPos], 20);
    this.startAnimation();
  },
  startAnimation: function () {
    var index = 0,
    that = this,
    bezier_points = that.linePos['bezier_points'],
    len = bezier_points.length - 1;
    this.setData({
      hide_good_box: false,
      bus_x: that.finger['x'],
      bus_y: that.finger['y']
    })
    this.timer = setInterval(function () {
      index++;
      that.setData({
        bus_x: bezier_points[index]['x'],
        bus_y: bezier_points[index]['y']
      })
      if (index >= len) {
        clearInterval(that.timer);
        that.setData({
          hide_good_box: true,
          selectedData: wx.getStorageSync('bookingGoodsData')
        })
        that.total(); // 计算总价
      }
    }, 15);
  },
})